﻿using System;
using System.Reflection;

using SceneEngine;

namespace SceneEditor
{
    public class EditPropertyAction : EditAction
    {
        PropertyInfo property;

        object[] oldValues;
        object[] newValues;

        string[] targets;

        public EditPropertyAction(string[] targets, object[] oldValues, string propertyName)
        {
            this.targets = targets;

            this.oldValues = oldValues;
            this.newValues = new object[oldValues.Length];

            for (int i = 0; i < targets.Length; i++)
            {
                BaseObject target = EngineGlobals.Scene.GetBaseObject(targets[i]);

                Type ownerType = target.GetType();
                property = ownerType.GetProperty(propertyName);

                newValues[i] = property.GetValue(target, null);
            }
        }

        public override void Undo()
        {
            for (int i = 0; i < targets.Length; i++)
            {
                BaseObject target = EngineGlobals.Scene.GetBaseObject(targets[i]);
                property.SetValue(target, oldValues[i], null);
            }
        }

        public override void Redo()
        {
            for (int i = 0; i < targets.Length; i++)
            {
                if (property.Name == "Name")
                {
                    BaseObject target = EngineGlobals.Scene.GetBaseObject(oldValues[i] as string);
                    property.SetValue(target, newValues[i], null);
                }

                else
                {
                    BaseObject target = EngineGlobals.Scene.GetBaseObject(targets[i]);
                    property.SetValue(target, newValues[i], null);
                }
            }
        }
    }
}
